package com.cskaoyan.demo6.servlet;


import com.cskaoyan.demo6.util.JsonUtil;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class CommonServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        // 从ServletContext中取出容器(listener那里初始化的)
        ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
        // 拿到当前Servlet所有的成员变量
        Field[] declaredFields = this.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            Class<?> type = declaredField.getType(); // UserService.class、OrderService.class、UserService.class、GoodsService.class
            // 找到Service成员变量
            if (type.getName().contains("Service")) {
                // 根据成员变量的类型从容器中取出这个类型的组件
                Object serviceBean = applicationContext.getBean(type);
                try {
                    declaredField.set(this, serviceBean); // field.set(instance,value)
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            common(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void common(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");


        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);

        Method method = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
        method.setAccessible(true);
        Object result = method.invoke(this, new Object[]{req, resp});
        if (result != null) {

            resp.getWriter().println(JsonUtil.write(result));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            common(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
